package com.example.studentmanagersystem;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.fs.adapters.AccountAdapter;
import com.fs.myview.UserListDialog;
import com.fs.po.UserData;
import com.fs.utils.GetDataHttpUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * @version 1
 * @author chenwenfei
 * date 2015-11-11
 *
 */
public class AdminAccountActivity extends Activity {

	private static final String ACTION1="admin_get_stu";
	private static final String ACTION2="admin_get_tec";
	private ListView listView;//user ListView
	private AccountAdapter m_RadioAdapter;//adapter
	private RadioGroup accountRadioGroup;//RadioGroup
	private Button accountSelectBtn;//select button
	private Button accountAdd;//add button
	
	private Button actionBack;
	private Button actionMenu;
	
	private List<UserData> list;
	private int checkedId;
	private GetDataHttpUtil dataHttpUtil;
	
	
	//head icon,get from service
	private int res[] = {R.drawable.icon1};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.admin_accountmanage_activity);
		
		this.createListView();//create ListView
		
		this.initView();//initialize view
		
		this.setAccountListener();//account listener

	}
	
	/**
	 * update UI
	 */
	Handler handler=new Handler(){
		
		public void handleMessage(Message msg) {
			
			if((msg.what==0)&&("stu".equals(msg.obj))){
				
				//invoking get student data
				getData(ACTION1);
				
			}else if((msg.what==0)&&("tec".equals(msg.obj))){
				
				//invoking get teacher data
				getData(ACTION2);
			}
			
		}
		
	};
	
	/**
	 * when last activity was destroy,the method will be invoking
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		if("stu".equals(user)){
			getData(ACTION1);
		}else if("tec".equals(user)){
			getData(ACTION2);
		}
		
	}


	/**
	 * ListView
	 */
	private void createListView() {
		this.listView = (ListView) this.findViewById(R.id.admin_account_activity_userListView);
		this.m_RadioAdapter = new AccountAdapter(this);//create adapter
		this.listView.setAdapter(m_RadioAdapter);//setting adapter
	}
	
	/**
	 * initialize widget
	 */
	private void initView() {
		
		this.accountRadioGroup=(RadioGroup) this.findViewById(R.id.admin_account_activity_RadioGroup);
		this.accountSelectBtn=(Button) this.findViewById(R.id.admin_account_activity_SearchUser);
		this.accountAdd=(Button) this.findViewById(R.id.admin_account_activity_newAdd);
		//back
		this.actionBack=(Button) this.findViewById(R.id.account_action_backButton);
		//menu
		this.actionMenu=(Button) this.findViewById(R.id.account_action_menu);
		
	}
	
	/**
	 * Listener,if select teacher,will get teacher data;if select student,will get student data 
	 * 设置监听事件,当选择老师、学生，就会获取到服务器的数据，当点击查找按钮时，将其显示到ListView中；
	 */
	
	private Intent intent;
	String user=null;
	private void setAccountListener() {
		//user select listener 用户选择监听
		this.accountRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				AdminAccountActivity.this.checkedId=checkedId;
				if(checkedId==R.id.admin_account_activity_stu){
					getData(ACTION1);
					user="stu";
				}else if(checkedId==R.id.admin_account_activity_tec){
					getData(ACTION2);
					user="tec";
				}
			}
		});
		//get user data 查找用户信息事件
		this.accountSelectBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if((checkedId==R.id.admin_account_activity_stu)){
					
					getData(ACTION1);
					
					m_RadioAdapter.setData(list,user,handler);
					 
				}else if(checkedId==R.id.admin_account_activity_tec){
					
					getData(ACTION2);
					m_RadioAdapter.setData(list,user,handler);
					
				}
				m_RadioAdapter.notifyDataSetChanged();
			}
		});
		
		//Add user 新增用户事件
		this.accountAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				intent=new Intent(AdminAccountActivity.this,AdminAccountAddUserActivity.class);
				startActivity(intent);
			}
		});
		
		
		//ListView Item Listener,if item is clicked,user info can be show列表项监听 ，当点击列表项时，就会弹出对话框用户展示用户的信息；
		this.listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
			
				if(list!=null){
					View diaologView=new UserListDialog(AdminAccountActivity.this,list.get(position)).setView();
					//create builder
					AlertDialog.Builder builder = new AlertDialog.Builder(AdminAccountActivity.this);
					//set attributes 设置属性
					builder.setView(diaologView);//设置对话框界面
					//create dialog 创建对话框
					AlertDialog alertDialog = builder.create();
					//show dialog 显示对话框
					alertDialog.show();
					alertDialog.getWindow().setLayout(600, 600); 
				}
			}
		});
		
		//action bar listener 导航栏返回按钮监听
		this.actionBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				 AdminAccountActivity.this.finish();
				
			}
		});
		
		//action menu listener 导航栏PopuMenu监听
		this.actionMenu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				 
				PopupMenuUtil popupMenuUtil=new PopupMenuUtil(v, AdminAccountActivity.this);
				popupMenuUtil.actionBackListener();
				
			}
		});
		
	}
	

	

	/**
	 * setting data,that will be from service 设置listView的显示数据,从服务器中获取
	 */
	private void getData(String action) {
		 
		list = new ArrayList<UserData>();
		int length = res.length;

			RequestParams params = new RequestParams();
			params.addBodyParameter("action", action);
			
			HttpUtils httpUtils=new HttpUtils();
			httpUtils.send(HttpMethod.POST,URL.SOCRE_URL, params, new RequestCallBack<String>() {

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {

					String jsonString=responseInfo.result;
					
					System.out.println("返回值"+jsonString);//【测试】
					
					setStuData(jsonString);
				}

				@Override
				public void onFailure(HttpException error, String msg) {
					
				}

			});
		
	}
	
	/**
	 * analysis 对数据进行解析
	 * @param jsonString
	 * @return
	 */
	public void setStuData(String jsonString) {

		Bitmap  bitmap = BitmapFactory.decodeResource(this.getResources(), res[0]);
		Drawable drawable=new BitmapDrawable(getResources(), bitmap);
		
		UserData userData=null;
		System.out.println(jsonString);
		if(jsonString!=null){

			try {
				JSONObject jsonObject = new JSONObject(jsonString);
				JSONArray array=jsonObject.getJSONArray(user);
				for(int i=0;i<array.length();i++){
					JSONObject json=array.getJSONObject(i);
					
					int user_id=Integer.parseInt(json.getString("_id"));
					String name=json.getString("name");
					String password=json.getString("password");
					String tel=json.getString("tel");
					String sex=json.getString("sex");
					int age=Integer.parseInt(json.getString("age"));
					
					if("tec".equals(user)){
						int class_id=Integer.parseInt(json.getString("class_id"));
						userData=new UserData(drawable,name, password,tel,sex,age,class_id,user_id);
					}else if("stu".equals(user)){
						userData=new UserData(drawable,name, password,tel,sex,age,0,user_id);
					}
					
					list.add(userData);
					
					m_RadioAdapter.setData(list,user,handler);
					 
					m_RadioAdapter.notifyDataSetChanged();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
	}

}
